<?php
/**
 * CmsController
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Admin\Controller;

use Admin\Service\BaseService;
use Admin\Service\PermissionService;
use Admin\Service\UserService;

use Model\WxUsersModel;
use Think\Controller;

/**
 * Class CmsController
 */
class WxController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $userService = new UserService();
        $userInfo = $userService->validateLogin();   //验证是否登录

        $permissionService = new PermissionService();
        $permission = $permissionService->validate($userInfo['userId'], [
            'getWxUsers' => '/' . CONTROLLER_NAME . '/getWxUsers',
            'sendTemplateMessage' => '/' . CONTROLLER_NAME . '/sendTemplateMessage',
        ]);
        $menu = $permissionService->menu($userInfo['userId']);
        $this->assign('permission', $permission);
        $this->assign('menu', $menu);
        $this->assign('userInfo', $userInfo);
    }

    public function index(){
        $model = new WxUsersModel();
        $page = $this->page($model, null);
        $show = $page->show();
        $limit[] = $page->firstRow;
        $limit[] = $page->listRows;
        $list = $model->findByFilter(null, ['id' => 'DESC'], $limit);
        $this->assign("page", $show);
        $this->assign('list', $list);
        $this->display();
    }

    public function getWxUsers()
    {
        $this->display();
//


    }

    public function getUsers()
    {
        set_time_limit(0);
        $wxId = C("WX_ID");
        $wxSecret = C("WX_SECRET");
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wxId . "&secret=" . $wxSecret;
        $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        $access_token = $result['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."";
        $res = file_get_contents($url);
        $result = json_decode($res, true);

        if(empty($result['data']['openid'])){
            $this->error("获取用户列表失败~");
        }

        $model = M("wx_users");
        M()->query($sql = 'TRUNCATE table `wx_users`');
        foreach($result['data']['openid'] as $k=>$v){
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$v."&lang=zh_CN";
            $res = file_get_contents($url);
            $result = json_decode($res, true);
            unset($result['tagid_list']);
            $model->add($result);
        }
        $count = count($result['data']['openid']);
        $sqlCount = $model->count();
        if($count == $sqlCount){
            $this->success("用户已全部获取成功！");
        }else{
            $this->error("用户获取数据丢失！！");
        }

    }

    public  function sendTemplateMessage(){
        $this->display();
    }

    public function dosendTemplateMessage(){
        set_time_limit(0);
        $courseName = I("post.courseName");
        $date = I("post.date");
        $remark = I("post.remark");
        $wxUsers = new WxUsersModel();
        $wxUlserList = $wxUsers->select();

        foreach($wxUlserList as $k=>$v){
            $status = $this->sendAllUsersTemplateMessage($courseName,$date,$remark,$v['nickname'],$v['openid']);
            if($status != 0){
                $this->error("群发消息失败~，终止至用户{$v['nickname']}");
            }

        }
        $this->success("群发消息成功!");

    }

    public function sendAllUsersTemplateMessage($courseName,$date,$remark,$nickName,$openid){
        $wxId = C("WX_ID");
        $wxSecret = C("WX_SECRET");
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wxId . "&secret=" . $wxSecret;
        $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
        $access_token = $result['access_token'];

        $customMessageSendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token."";
        $postDataArr['touser'] = "".$openid."";
        $postDataArr['template_id'] ="9166RP57atMbnTARJE-2C1aWI-qL_BtUaH575g4atpQ";
        $postDataArr['url'] ="http://www.baidu.com";
        $postDataArr['data'] =  array(
            'userName'=>array("value"=>"".$nickName."","color"=>"#1fe3b3"),
            'courseName'=>array("value"=>"".$courseName."","color"=>"#1fe3b3"),
            'date'=>array("value"=>"".$date."","color"=>"#1fe3b3"),
            'remark'=>array("value"=>"".$remark."","color"=>"#e33b5a"),
        );
        $postJosnData = json_encode($postDataArr);
        $ch = curl_init($customMessageSendUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        $data = json_decode($data,true);
        return $data['errcode'];

    }


}